package com.yyq.sos.logs;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.hibernate.Hibernate;

import com.yyq.servlets.ApplicationContextHandle;
import com.yyq.sos.dao.SysLogsDao;
import com.yyq.sos.permission.LoginUser;
import com.yyq.sos.pojo.SysLogs;
import com.yyq.sos.util.SysParametersUtil;


public class LogerImpl extends Logger {
	static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
	static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	String tableName;
	private SysLogsDao logsDao;
	
	
	
	public LogerImpl(){
		logsDao = (SysLogsDao)ApplicationContextHandle.getBean("sysLogsDao");
	}
	
	private SysLogs processUserLogs(String tableName,String actionType,String result){
		LoginUser user = (LoginUser)LoginUser.userThread.get();
		if(user == null){
			user = new LoginUser();
			user.setUserCname("用户不存在！");
			user.setUserId(new Long(-1));
			user.setUserName("no user");
		}
		SysLogs log = new SysLogs();
		log.setTableName(tableName.toUpperCase());
		log.setUserId(user.getUserId());
		log.setUserName(user.getUserName());
		log.setUserCname(user.getUserCname());
		log.setActionType(actionType);
		log.setBeginTime(new Date());
		log.setActionResult(result.toUpperCase());
		return log;
	}
	
	/**
	 * 日志记录，操作表，操作类型，操作结果(success/fail)，操作内容(处理数据或错误信息)
	 * @param talbe 操作表
	 * @param actionType  操作类型
	 * @param result  操作结果(success/fail)
	 * @param content 操作内容(处理数据或错误信息)
	 */
	public void log(String table, String actionType,String result,String content){
		SysLogs log = this.processUserLogs(table, actionType, result);
		log.setLogContext(Hibernate.createBlob(content.getBytes()));
		logsDao.add(log);
	}
	/**
	 * 日志记录，操作表，操作类型，操作结果(success/fail)，操作内容(处理数据或错误信息)
	 * @param talbe 操作表
	 * @param actionType  操作类型
	 * @param result  操作结果(success/fail)
	 * @param content 操作内容(处理数据或错误信息)
	 */
	public void log(String table, String actionType,String result,String content,int type){
		if(type == LoggerProxy.SAVE_TO_FILE){
			String deletedPath = SysParametersUtil.getInstance().getValue("DELETED_LOG_PATH");
			if(deletedPath == null){
				deletedPath = "d:/logs";
			}
			String fileName = sdf.format(new Date());
			File filePath = new File(deletedPath);
			if(!filePath.exists()){
				filePath.mkdirs();
			}
			BufferedWriter bw = null;
			try {
				bw = new BufferedWriter(new FileWriter(new File(deletedPath+File.separator+fileName),true));
				bw.write(sdf2.format(new Date())+":");
				bw.newLine();
				LoginUser user = (LoginUser)LoginUser.userThread.get();
				if(user != null){
					content=user.getUserCname()+":"+actionType+"\t"+content+"\t"+result;
				}else{
					content="不明用户:"+actionType+"\t"+content+"\t"+result;
				}
				bw.write(content);
				bw.newLine();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if(bw != null){
						bw.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}else{
			log(table,actionType,result,content);
		}
	}
	
	public Logger setTableClass(Class cls,String tableName){
		if(cls!=null){
			this.tableName = logsDao.getTableName(cls);
		}else
			this.tableName = tableName;
		return this;
	}
	
	public void log(String actionType, String logResult,List beforeList, List afterList) {
		StringBuffer context = new StringBuffer("\r\n修改前数据:\r\n");
		for(int i=0; i<beforeList.size(); ++i){
			context.append(beforeList.get(i).toString());
		}
		context = new StringBuffer("\r\n修改后数据:\r\n");
		for(int i=0; i<afterList.size(); ++i){
			context.append(afterList.get(i).toString());
		}
		SysLogs log = this.processUserLogs(tableName, actionType, logResult);
		log.setLogContext(Hibernate.createBlob(context.toString().getBytes()));
		logsDao.add(log);
	}
	
	public void log(String actionType, String logResult,List objCtx) {
		StringBuffer context = new StringBuffer("\r\n已处理数据:\r\n");
		for(int i=0; i<objCtx.size(); ++i){
			context.append(objCtx.get(i).toString());
		}
		SysLogs log = this.processUserLogs(tableName, actionType, logResult);
//		log.setLogContext(context.toString());
		log.setLogContext(Hibernate.createBlob(context.toString().getBytes()));
		logsDao.add(log);
	}
	
	public void log(String actionType, String logResult,Object updateBeforeObj, Object updateAfterObj) {
		StringBuffer context = new StringBuffer("\r\n修改前数据:\r\n");
		context.append(updateBeforeObj.toString());
		context.append("\r\n修改后数据:\r\n");
		context.append(updateAfterObj.toString());
		SysLogs log = this.processUserLogs(tableName, actionType, logResult);
		log.setLogContext(Hibernate.createBlob(context.toString().getBytes()));
		logsDao.add(log);
	}
	
	public void log(String actionType, String result,Object obj) {
		StringBuffer context = new StringBuffer("\r\n已处理数据:\r\n");
		context.append(obj.toString());
		SysLogs log = this.processUserLogs(tableName, actionType, result);
		log.setLogContext(Hibernate.createBlob(context.toString().getBytes()));
		logsDao.add(log);
	}
	
	public void log(String actionType, String result) {
		SysLogs log = this.processUserLogs(tableName, actionType, result);
		logsDao.add(log);
	}

	
}
